from flask import Blueprint, request
from flask_restful import Api, Resource, marshal_with, inputs
from flask_restful.reqparse import RequestParser

from utils.render import json_detail_render
from webapp.config import api_utils
from webapp.config.api_utils import oper_log, check_auth, datetime_parse
from webapp.dto_mapper import teacher_page_fields, \
    teacher_time_fields
from webapp.service.teacher_service import TeacherService

teacher_app = Blueprint('teacher', __name__, url_prefix='/api/teacher')
teacher_api = Api(teacher_app)


def phone_type(value):
    if value is None:
        return value
    elif isinstance(value, int):
        return inputs.regex(r'^1[3|4|5|7|8|9][0-9]\d{8}$')(str(value))
    return inputs.regex(r'^1[3|4|5|7|8|9][0-9]\d{8}$')(value)


parser = RequestParser()
parser.add_argument('id', location='json', type=int, required=True)
parser.add_argument('username', location='json', type=str, trim=True, required=True)
parser.add_argument('nickName', location='json', type=str, trim=True, required=True)
parser.add_argument('gender', location='json', type=str, choices=('男', '女'),
                    help='无效的选项: {error_msg}')
parser.add_argument('email', location='json', type=inputs.regex(
    r'^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'),
                    trim=True, required=True, help='格式错误: {error_msg}')
parser.add_argument('enabled', location='json', type=inputs.boolean,
                    choices=('true', 'false', 'True', 'False', True, False),
                    help='无效的选项: {error_msg}', trim=True, required=True)
parser.add_argument('phone', location='json', type=phone_type, trim=True,
                    help='格式错误: {error_msg}')
parser.add_argument('createBy', location='json', type=str, trim=True)
parser.add_argument('updatedBy', location='json', type=str, trim=True)
parser.add_argument('createTime', location='json', type=datetime_parse, trim=True)
parser.add_argument('updateTime', location='json', type=datetime_parse, trim=True)
parser.add_argument('deptId', location='json', type=int)
parser.add_argument('avatarName', location='json', type=str, trim=True)
parser.add_argument('avatarPath', location='json', type=str, trim=True)
parser.add_argument('pwdResetTime', location='json', type=datetime_parse, trim=True)
parser.add_argument('roles', location='json', type=list)
parser.add_argument('jobs', location='json', type=list)
parser.add_argument('dept', location='json', type=dict)
roles_parser = RequestParser()
roles_parser.add_argument('id', location='roles', type=int)
jobs_parser = RequestParser()
jobs_parser.add_argument('id', location='jobs', type=int)
dept_parser = RequestParser()
dept_parser.add_argument('id', location='dept', type=int)
dept_parser.add_argument('name', location='dept', type=str, trim=True)


@teacher_api.resource("", "/")
class TeacherApi(Resource):

    @oper_log('查询所有老师', request)
    @check_auth('teacher:list', request)
    @marshal_with(teacher_page_fields)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = api_utils.build_params(params)
        pagination = TeacherService.query_all(**params_dict)
        return pagination


@teacher_api.resource("", "/<int:id>")
class TeachTimeSettingApi(Resource):
    @oper_log('设置老师可上课时间', request)
    @check_auth('teacher:edit', request)
    def post(self, id):
        params = request.get_json()
        TeacherService.timeSetting(id, params)
        return json_detail_render(0, message="设置成功!")

    @oper_log('返回已经设置的上课时间', request)
    @check_auth('teacher:list', request)
    @marshal_with(teacher_time_fields)
    def get(self, id):
        teacherbindtime = TeacherService.find_by_teacherid(id)
        return teacherbindtime